<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: 'home' }">过程任务</el-breadcrumb-item>
      <el-breadcrumb-item>我的发布</el-breadcrumb-item>
    </el-breadcrumb>

    <h2 style="border-bottom: 1px solid;padding-bottom: 10px;">我的发布</h2>
    <div style="margin: 3% 5% 3% 5%;">
      <h1>我的发布</h1><el-button type="primary" @click="toprocessPublish">发布任务</el-button>
      <div style="margin-top:2%;  "><!-- 收到的小队邀请 -->
        <el-table :data="processTask" height="250" border stripe style="width: 100%; height:250px;">
          <el-table-column align="center" type="index" label="序号" width="55" />
          <el-table-column prop="courseName" label="实践课程" />
          <el-table-column prop="processName" label="任务名称" />
          <el-table-column prop="className" label="班级" />
          <el-table-column prop="startDate" label="开始时间" :formatter="formatDate" />
          <el-table-column prop="endDate" label="截止时间" :formatter="formatDate" />
          <el-table-column prop="processType" label="过程类型" :formatter="formatType" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="toDetail(scope.row.processId)">查看</el-button>
              <el-button link type="danger" size="small" @click="toDelete(scope.row.processId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 任务详情 -->
    <h2 style="border-bottom: 1px solid;padding-bottom: 10px;">任务详情</h2>
    <div v-if="getStuStatus.length != 1">
      <div style="margin: 3% 5% 3% 5%;">
        <!-- 选题详情 -->
        <div>
          <el-descriptions title="选题详情" column="1" size="large">
            <el-descriptions-item label="任务名称" width="200px">{{ taskDetial.processName }}</el-descriptions-item>
            <el-descriptions-item label="专业">{{ taskDetial.classMajorName }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <h1>班级详情</h1>
        <div style="margin-top:2%;height: 500px" ><!-- 收到的小队邀请 -->
          <el-table :data="getStuStatus" height="455" border stripe style="width: 100%;">
            <el-table-column prop="stuId" label="学号" />
            <el-table-column prop="stuName" label="学生姓名" />
            <el-table-column prop="className" label="班级" />
            <el-table-column prop="createTime" label="提交时间" :formatter="formatStuDate" />
            <el-table-column fixed="right" label="报告" width="120">
              <template #default="scope">
                <el-button link type="primary" size="small"
                  @click="doewnFile(scope.row.stuPhone, scope.row.processId, scope.row.filename)"
                  v-if="scope.row.filename != null">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 提示选择任务 -->
    <div v-if="getStuStatus.length == 1" style="background-color: #F5F7FA;">
      <h1 style="font-size: 32px; font-weight: bold; margin-top: 3%; text-align: center; background-color: #F5F7FA;">
        请先选择过程任务</h1>
    </div>

  </div>
</template>
<script setup>
import { ref, onBeforeMount, computed } from 'vue';
import { ArrowRight } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import requests from '@/api/ajax';


onBeforeMount(() => {
  const asd = requests({ url: "inner/myInnerProcessTask", method: "get", }).then(res => {
    //存储用户信息到浏览器toke
    const abc = res.rdata
    processTask.value = abc

  })
    .catch(err => {
      console.error(err.data);
      // 登录请求失败后的操作
    });
})

//页面跳转到发布
const router_useRouter = useRouter()

function toDetail(processId) {
  // router_useRouter.push({
  //   path: 'innerProDetail',
  //   query: { processId: id }
  // })
  // $router.push(`courseTaskDetail/${scope.row.practicalId}`)
  const getStu = requests({ url: "/inner/processTask/" + processId, method: "get", }).then(res => {
    //存储用户信息到浏览器toke
    if (res.code === 20041) {
      getStuStatus.value = res.rdata
    } else {
      getStuStatus.value = null
    }


  })
    .catch(err => {
      console.error(err);
      // 登录请求失败后的操作
    });
}


function toprocessPublish() {
  router_useRouter.push({ path: 'innerProPublish' })
}

//老师发布的过程任务
const processTask = ref([
  {
    processId: '',
    processName: "",
    processType: '',
    startDate: "",
    endDate: "",
    content: "",
    practicalId: '',
    classId: '',
    className: "",
    adviserId: '',
    adviserName: "",
    teachId: '',
    teachName: "",
    practicalType: '',
    onloadDate: ""
  }
])

//时间格式化
function formatDate(row, column, cellValue, index) {
  let format = 'YYYY-mm-dd'
  let date = new Date(cellValue);
  const dataItem = {
    'Y+': date.getFullYear().toString(),
    'm+': (date.getMonth() + 1).toString(),
    'd+': date.getDate().toString(),
  }
  Object.keys(dataItem).forEach((item) => {
    const ret = new RegExp(`(${item})`).exec(format);
    if (ret) {
      format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
    }
  });
  return format
}

//学生提交信息
const getStuStatus = ref([
  {
    processId: '',
    processName: "",
    processType: '',
    startDate: "",
    endDate: "",
    content: "",
    scoreStart: "",
    scoreEnd: "",
    practicalId: '',
    classId: '',
    className: "",
    adviserId: '',
    adviserName: "",
    teachId: '',
    teachName: '',
    practicalType: '',
    onloadDate: '',
    planId: '',
    courseId: '',
    courseName: '',
    majorName: '',
    enrolDate: '',
    filename: "",
    stuId: '',
    stuName: "",
    stuSex: '',
    stuIdentity: '',
    stuCollege: '',
    stuPhone: "",
    classMajorName: "",
    classGraduateDate: ''
  }
])

//时间格式化
function formatStuDate(row, column, cellValue, index) {
  let format = 'YYYY-mm-dd h:i'
  let date = new Date(cellValue);
  if (cellValue != null) {
    const dataItem = {
      'Y+': date.getFullYear().toString(),
      'm+': (date.getMonth() + 1).toString(),
      'd+': date.getDate().toString(),
      'h+': date.getHours().toString().padStart(2,"0"),
      'i+': date.getMinutes().toString().padStart(2,"0"),
    }
    Object.keys(dataItem).forEach((item) => {
      const ret = new RegExp(`(${item})`).exec(format);
      if (ret) {
        format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
      }
    });
    return format
  } else {
    const nothing = ('未提交')
    return nothing
  }

}

//将任务类型转换为过程任务或最终任务
function formatType(row, column, cellValue, index) {
    let format = ''
    let date = cellValue;
    if (date === 0) {
        format = '过程任务';
    } else if (date === 1) {
        format = '最终任务';
    }
    return format;
}


//过程任务信息
const taskDetial = ref({
  processName: '',
  majorName: '',
  startDate: '',
  endDate: '',
})

taskDetial.value.processName = computed(() => getStuStatus.value[0].processName)
taskDetial.value.classMajorName = computed(() => getStuStatus.value[0].classMajorName)

const startStr = computed(() => getStuStatus.value[0].startDate);
taskDetial.value.startDate = computed(() => startStr.value.substring(0, 10));

const endStr = computed(() => getStuStatus.value[0].endDate);
taskDetial.value.endDate = computed(() => endStr.value.substring(0, 10));


//下载报告
function doewnFile(appraiseePhone, processId, filename) {
  if (filename != null) {
    const getReport = requests({ url: "/preview/processTask/" + appraiseePhone + "/" + processId, method: "get", responseType: 'blob', }).then(res => {
      // const blob = new Blob([res.rdata], { type: res.rdata.type });
      // saveAs(blob, 'example.docx');

      // 将响应数据转换为 Blob 对象
      const blob = new Blob([res]);
      // 创建链接进行下载
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    })
      .catch(err => {
        console.error(err);
        // 登录请求失败后的操作
      });
  } else {
    alert('该学生未提交报告')
  }
}

//删除过程任务
const toDelete = (processId) => {
  ElMessageBox.confirm(
    '是否确认删除？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

      const getStu = requests({ url: "/inner/ProcessTask/" + processId, method: "delete", }).then(res => {
        //存储用户信息到浏览器toke
        if (res.code === 20021) {
          ElMessage({
            message: res.msg,
            type: 'success',
          })

          const asd = requests({ url: "inner/myInnerProcessTask", method: "get", }).then(res => {
            //存储用户信息到浏览器toke
            const abc = res.rdata
            processTask.value = abc

          })
            .catch(err => {
              console.error(err.data);
              // 登录请求失败后的操作
            });
        } else {
          getStuStatus.value = null
        }


      })
        .catch(err => {
          console.error(err);
          // 登录请求失败后的操作
        });
    })

}

</script>